package ichubcache

import (
	"gitee.com/ichub/goconfig/common/base/basedto"
	"github.com/patrickmn/go-cache"
)

import "time"

func CacheGet[T any](Key string) (*T, bool) {
	v, found := FindBeanIchubCache().gocache.Get(Key)
	if found {
		return v.(*T), found
	}
	return nil, false
}

func CacheSet[T any](Key string, object *T) {
	FindBeanIchubCache().gocache.Set(Key, object, 10*time.Minute)

}

type IchubCache struct {
	basedto.BaseEntitySingle

	gocache    *cache.Cache `json:"-"`
	Pkey       string
	ExpireTime time.Duration
}

func NewCache() *IchubCache {
	return NewIchubCache("ichub:")
}
func NewIchubCache(Pkey string) *IchubCache {
	return &IchubCache{
		Pkey:       Pkey,
		ExpireTime: Cache_expire_time,
		// 默认过期时间10s；清理间隔30s，即每30s钟会自动清理过期的键值对
		gocache: cache.New(Cache_expire_time, cache_clean_time),
	}
}

func (this *IchubCache) Set(k string, x interface{}, d time.Duration) {
	this.gocache.Set(this.Pkey+k, x, d)
}

func (this *IchubCache) Get(k string) (interface{}, bool) {
	return this.gocache.Get(this.Pkey + k)
}
